<template>
  <view class="drug">
    <view v-for="(item, index) in orderList" :key="index" class="d-item">
      <view v-if="item.drugs && item.drugs.length" class="clearfix">
        <view class="d-i-title">
          需求编号:{{ item.orderNo }}<view class="d-i-status">{{ item.status | statusFilter }}</view>
        </view>
        <view @click="goDetail(item)">
          <view v-for="(drug, index) in item.drugs" :key="index" class="drug-list">
            <image class="drug-img" mode="aspectFit" :src="drug.outerPackagePicUrl" />
            <view class="drug-info">
              <view v-if="drug.productName" class="title">{{ drug.commonName }} ({{ drug.productName }})</view>
              <view v-else class="title">{{ drug.commonName }}</view>
              <view class="drug-num">
                <view class="spe">
                  {{ drug.preparationUnit }}*{{ drug.packageSize }}{{ drug.minimumUnit }}/{{ drug.packageUnit }}
                </view>
                <view class="drug-amount">x{{ drug.amount }}</view>
              </view>
            </view>
          </view>
        </view>

        <view
          v-if="!item.isPay && item.status !== 99 && item.status !== 98"
          class="drug-payment"
          @click="payment(item)"
        >
          支 付
        </view>
      </view>
    </view>
    <view class="zhanwei"></view>
  </view>
</template>
<script>
import { getDrugOrder, orderPay } from '@/api/drugInfo';
import { memberId } from '@/common/baseUrl';

//
export default {
  filters: {
    statusFilter: function (value) {
      let status = {
        10: '已登记',
        20: '未预约',
        30: '已预约',
        35: '处理中',
        40: '处理中',
        45: '处理中',
        50: '处理中',
        60: '已完成',
        70: '已完成',
        97: '已驳回',
        98: '已撤销',
        99: '已完成'
      };
      return status[value];
    }
  },
  data() {
    return {
      orderList: [],
      patientId: null
    };
  },
  onLoad(option) {
    let patientId = (option && option.patientId) || this.$store.state.join.patientid;
    this.patientId = patientId;
    /* ------------- */
    // this.patientId = '3dd45d7114af46ce80f9776c15083f66';
    if (!this.patientId) {
      this.patientId = this.$store.state.assessQuestion.scTime;
    }
    this.init();
  },
  methods: {
    async init() {
      getDrugOrder(this.patientId).then((res) => {
        if (res.code !== 0) {
          uni.showModal({
            title: '提示',
            content: '获取用药订单信息失败'
          });
        } else {
          this.orderList = res.data.list;
          console.log(res.data.list);
        }
      });
    },

    goDetail(item) {
      // 查看订单详情
      this.$wxPromise.navigateTo({
        url: '/pages/drugOrder/detail?orderId=' + item.id + '&patientId=' + this.patientId
      });
    },

    // 支付
    async payment(item) {
      uni.showLoading({
        title: '加载中',
        mask: true
      });
      const payParams = [
        {
          largeClass: 2, // 支付大类(固定值)
          groupId: 22, // 支付中类(固定值)
          paytypeId: 22, // 支付小类(固定值)
          amount: (item.amount / 100 || 0).toFixed(2), // 金额
          freightAmount: (item.freight / 100 || 0).toFixed(2), // 金额
          memberId: memberId, // 如果微信支付传memberId
          openId: wx.getStorageSync('openid'), // 微信openId
          appId: wx.getStorageSync('appid') // 微信appId
        }
      ];
      const pay_res = await orderPay(item.id, payParams);
      uni.hideLoading();
      if (pay_res.code !== 0) {
        uni.showModal({
          title: '提示',
          content: '调用支付失败',
          showCancel: false
        });
        return;
      }

      const time = item.deliveryTime.split(' ')[0];
      const doc = JSON.parse(pay_res.data.payInfo);
      let params = {
        appId: doc.appId,
        nonceStr: doc.nonceStr,
        package: doc.package, // 固定值，以微信支付文档为主
        timeStamp: doc.timeStamp,
        paySign: doc.paySign,
        signType: doc.signType // 根据签名算法生成签名
      };
      uni.requestPayment({
        provider: 'wxpay',
        ...params,
        success: (win) => {
          uni.showToast({
            title: '支付成功，跳转中',
            icon: 'none',
            mask: true
          });
          setTimeout(() => {
            const params = `pages/registerResult/index?time=${time}&patientId=${item.patientId}&result=1`;
            uni.reLaunch({
              url: params
            });
          }, 1500);
        },
        fail: function (err) {
          const d1 = JSON.stringify(payParams);
          uni.showToast({
            title: '支付失败，跳转中',
            icon: 'none',
            mask: true
          });
          setTimeout(() => {
            const params = `pages/registerResult/index?time=${time}&patientId=${item.patientId}&result=0&orderId=${item.id}&pay=${d1}`;
            uni.reLaunch({
              url: params
            });
          }, 1500);
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.drug {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  .zhanwei {
    height: 60rpx;
  }
  .d-item {
    background: white;
    width: 700rpx;
    margin: auto;
    margin-top: 24rpx;
    padding: 24rpx;
    box-sizing: border-box;
    border-radius: 12rpx;
    .d-i-title {
      font-size: 28rpx;
      color: rgb(102, 102, 102);
      margin-bottom: 24rpx;
      .d-i-status {
        float: right;
        color: #f34e1c;
      }
    }
    .drug-list {
      border-radius: 24rpx;
      background: #ffffff;
      display: flex;
      margin-bottom: 24rpx;
      .drug-img {
        width: 120rpx;
        height: 120rpx;
      }
      .drug-info {
        flex: 1;
        margin-left: 28rpx;
        font-size: 28rpx;
        color: rgba(0, 0, 0, 0.55);
        position: relative;
      }
      .title {
        max-height: 80rpx;
        font-size: 32rpx;
        line-height: 1.3em;
        color: rgba(0, 0, 0, 0.9);
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      .drug-num {
        display: flex;
        justify-content: space-between;
        font-size: 28rpx;
        color: rgba(0, 0, 0, 0.3);
        margin-top: 10rpx;
        overflow: hidden;
        .spe {
        }
        .drug-num {
        }
      }
    }
  }
  &-payment {
    width: 150rpx;
    height: 66rpx;
    border: 1px solid #f34e1c;
    border-radius: 44rpx;
    color: #f34e1c;
    font-size: 32rpx;
    text-align: center;
    line-height: 66rpx;
    float: right;
    margin: 10rpx 0;
  }
  .clearfix::after {
    content: ' ';
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;
  }
}
</style>
